package com.dh.convert.node;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import com.dh.convert.utils.ClassUtils;
import com.fasterxml.jackson.databind.JsonNode;

public class CollectionNode extends ArrayNode {

	@Override
	protected Class<?> getEntryClass(Field f) {
		return ClassUtils.getListType(f);
	}

	@Override
	public Object genObject(JsonNode jn, Object targetObject, Object currentObject,Map<String, Object> context)
			throws InstantiationException, IllegalAccessException {
		Collection o = null;
		if (_isRoot)
			o = (Collection) targetObject;
		else if(currentObject!=null){
			o = (Collection) currentObject;
		}else if (currentClass.isInterface()) {
			if (Set.class.isAssignableFrom(currentClass)) {
				o = new TreeSet<>();
			} else if (List.class.isAssignableFrom(currentClass)) {
				o = new ArrayList<>();
			}
		} else{
			o = (Collection) currentClass.newInstance();
		}
		return genList(jn, targetObject, o, context);
	}

	@Override
	public TreeNode bulid(Field f) {
		super.bulid(f);
		this._isColltion = Boolean.TRUE;
		return this;
	}
}
